package pl.com.qapps.datastore.berkeley;

import java.io.PrintStream;
import java.util.Objects;

import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.OperationStatus;

public class BerkeleyUtils {

	public static void dbDump(Database db) {
		dbDump(db, false);
	}

	public static void dbDump(Database db, boolean keysOnly) {
		dbDump(db, keysOnly, System.out);
	}
	
	// TODO implement keys only
	public static void dbDump(Database db, boolean keysOnly, PrintStream out) {
		Objects.requireNonNull(db, "dbcannot be null");

		DatabaseEntry key = new DatabaseEntry();
		DatabaseEntry data = new DatabaseEntry();

		long count = 0;
		Cursor cursor = null;
		try {
			out.println("======== DB DUMP =========| " + db.getDatabaseName()
					+ " |===============================>>>>>>>");

			cursor = db.openCursor(null, null);
			while (cursor.getNext(key, data, null) == OperationStatus.SUCCESS) {
				out.println("	" + new String(key.getData(), 0, key.getSize() - 1) + " => " + new String(data.getData(), 0, data.getSize() - 1));
//				out.println("	" + Arrays.toString(key.getData()) + " => " + Arrays.toString(data.getData()));
				count++;
			}
			
			out.println("<<<<<<===========|" + count + "|=======================================================");
		} catch (Exception e) {
			e.printStackTrace(out);
		} finally {
			if (cursor != null)
				cursor.close();
		}
	}

}
